package com.weimob.mcloud.wechatwork.customer.mq.handler.tag;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.weimob.mcloud.wechatwork.common.enums.CommonBizErrorEnum;
import com.weimob.mcloud.wechatwork.common.enums.MainBizDomainEnum;
import com.weimob.mcloud.wechatwork.common.enums.SubBizDomainEnum;
import com.weimob.mcloud.wechatwork.common.utils.BizErrorCodeGenerator;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.channel.response.CorpTagGroup;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.channel.response.CorpTagInfo;
import com.weimob.mcloud.wechatwork.core.entity.privatesphere.PrivateSphere;
import com.weimob.mcloud.wechatwork.core.entity.relation.tag.Tag;
import com.weimob.mcloud.wechatwork.core.entity.relation.tag.TagGroup;
import com.weimob.mcloud.wechatwork.core.service.privatesphere.PrivateSphereService;
import com.weimob.mcloud.wechatwork.customer.domain.ExternalUserChangeInfo;
import com.weimob.mcloud.wechatwork.customer.mq.handler.externaluser.CorpExternalUserHandler;
import com.weimob.mcloud.wechatwork.customer.mq.product.TagChangeMsgProduct;
import com.weimob.mcloud.wechatwork.customer.service.TagBaseService;
import com.weimob.mcloud.wechatwork.customer.service.user.constant.TagConstant;
import com.weimob.mcloud.wechatwork.customer.service.user.enums.TagSourceEnum;
import com.weimob.mcloud.wechatwork.customer.service.user.enums.tag.TagChangeEnum;
import com.weimob.mcloud.wechatwork.customer.service.user.module.msgBody.TagChangeBody;
import com.weimob.mcloud.wechatwork.customer.third.BosThird;
import com.weimob.mcloud.wechatwork.customer.third.tag.CorpTagThird;
import com.weimob.soa.common.response.SoaResponse;
import com.weimob.soa.common.utils.SoaUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Set;

@Service
@Slf4j
public class CreateTagHandler implements CorpExternalUserHandler {

    @Autowired
    private CorpTagThird corpTagThird;

    @Autowired
    private BosThird bosThird;

    @Autowired
    private TagBaseService tagBaseService;

    @Autowired
    private TagChangeMsgProduct tagChangeMsgProduct;

    @Reference
    private PrivateSphereService privateSphereService;

    /**
     * 企微助手产品id
     */
    @Value("${aewc.productId:203}")
    private Long aewcProductId;

    /**
     * 标签新增处理
     */
    @Override
    public SoaResponse<?, ?> handleCorpExternalUser(ExternalUserChangeInfo tagChangeInfo) {
        log.info("tag create message start,request:{}", JSON.toJSONString(tagChangeInfo));
        String corpId = tagChangeInfo.getToUserName();
        String templateId = tagChangeInfo.getTemplateId();

        PrivateSphere privateSphereRequest = new PrivateSphere();
        privateSphereRequest.setCorpId(corpId);
        privateSphereRequest.setProductId(aewcProductId);
        privateSphereRequest.setTemplateId(templateId);
        SoaResponse<PrivateSphere, Void> fetchPrivateSphere = privateSphereService.fetch(privateSphereRequest);
        if (0L != Long.parseLong(fetchPrivateSphere.getReturnCode()) || Objects.isNull(fetchPrivateSphere.getResponseVo())) {
            //1.1、私域不存在，返回（不落非企微产品外部联系人数据）
            log.info("消费新增外部联系人消息查询私域信息失败,corpId:{}, aewcProductId:{}", corpId, aewcProductId);
            String errorCode = BizErrorCodeGenerator.generate(MainBizDomainEnum.CUSTOMER_MANAGEMENT
                    , SubBizDomainEnum.CUSTOMER_TAG, CommonBizErrorEnum.ILLEGAL_ARGUMENTS);
            return SoaUtil.error(errorCode, "消费新增外部联系人消息查询私域信息失败", null);
        }
        PrivateSphere privateSphere = fetchPrivateSphere.getResponseVo();

        try {
            createTag(privateSphere, tagChangeInfo);
        } catch (Exception e) {
            log.error("tag create message handle error, privateSphere:{}, request:{}, error:{}", JSON.toJSONString(privateSphere),
                    JSON.toJSONString(tagChangeInfo), e);
        }

        return SoaUtil.ok(null);
    }

    public void createTag(PrivateSphere privateSphere, ExternalUserChangeInfo tagChangeInfo) {

        //这里只接收标签创建的消息，接受标签组创建的消息没有意义，因为有标签必定能拿到标签组
        if (tagChangeInfo.getTagType().equals(TagConstant.TAG_CHANGE)) {
            log.info("tag create message start, corpId:{}, bosId:{}, tagChangeInfo:{}",
                    privateSphere.getCorpId(), privateSphere.getBosId(), JSON.toJSONString(tagChangeInfo));

            CorpTagGroup corpTagGroup = corpTagThird.getChannelTagGroup(privateSphere, TagConstant.TAG_CHANGE, tagChangeInfo.getId());
            if (Objects.isNull(corpTagGroup) || CollectionUtils.isEmpty(corpTagGroup.getTagList())) {
                return;
            }

            List<TagGroup> tagGroupList = tagBaseService.queryGroupByGroupIds(privateSphere.getCorpId(), Lists.newArrayList(corpTagGroup.getGroupId()));
            if (CollectionUtils.isEmpty(tagGroupList)) {
                //创建标签组
                TagGroup tagGroup = new TagGroup();
                tagGroup.setCorpId(privateSphere.getCorpId());
                tagGroup.setExternalTagGroupId(corpTagGroup.getGroupId());
                tagGroup.setTagGroupName(corpTagGroup.getGroupName());
                tagGroup.setTagSource(TagSourceEnum.WECHAT.getSource());
                tagGroup.setDeleted(false);
                tagGroup.setPrivateSphere(privateSphere);
                tagBaseService.batchInsertTagGroup(Lists.newArrayList(tagGroup), privateSphere.getCorpId());
            }

            CorpTagInfo corpTagInfo = corpTagGroup.getTagList().get(0);
            TagGroup tagGroup = new TagGroup();
            tagGroup.setCorpId(privateSphere.getCorpId());
            tagGroup.setExternalTagGroupId(corpTagGroup.getGroupId());
            tagGroup.setTagGroupName(corpTagGroup.getGroupName());
            tagGroup.setTagSource(TagSourceEnum.WECHAT.getSource());
            tagGroup.setPrivateSphere(privateSphere);

            Tag tag = new Tag();
            tag.setCorpId(privateSphere.getCorpId());
            tag.setTagGroup(tagGroup);
            tag.setTagSource(TagSourceEnum.WECHAT.getSource());
            tag.setExternalTagId(corpTagInfo.getTagId());
            tag.setTagName(corpTagInfo.getTagName());
            tag.setDeleted(false);
            tag.setPrivateSphere(privateSphere);
            tagBaseService.batchInsertTag(Lists.newArrayList(tag), privateSphere.getCorpId());

            Set<Long> bosIds = bosThird.getBosIdListByCorpId(privateSphere.getCorpId());
            if (CollectionUtils.isEmpty(bosIds)) {
                log.error("实时监听企微官方添加标签消息, 根据corpId查询bosId, 没有查到, corpId:{}", privateSphere.getCorpId());
                return;
            }

            for (Long bosId : bosIds) {
                //发送企微官方标签变更数据,目前只有cdp在消费，如果后续有其他业务在使用，建议在这里说明
                TagChangeBody tagChangeBody = new TagChangeBody();
                tagChangeBody.setBosId(bosId);
                tagChangeBody.setCorpId(privateSphere.getCorpId());
                tagChangeBody.setCorpTagGroupId(corpTagGroup.getGroupId());
                tagChangeBody.setTagGroupName(corpTagGroup.getGroupName());
                tagChangeBody.setCorpTagId(corpTagInfo.getTagId());
                tagChangeBody.setTagName(corpTagInfo.getTagName());
                tagChangeBody.setTagChangeType(TagChangeEnum.TAG_CREATE.getType());
                try {
                    tagChangeMsgProduct.sendTagChangeMsg(tagChangeBody);
                } catch (Exception e) {
                    log.error("同步企微官方标签创建, 发送消息失败, msgBody:{}, error:{}", JSON.toJSONString(tagChangeBody), e);
                }
            }
        }
    }

}
